﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using antuAutoUPTools.Entries;
using System.Threading;
using System.Configuration;
using antuAutoUPTools.Business;

namespace antuAutoUPTools
{
    public partial class AutoUpTools : Form
    {
        //上传设置
        private UpSetting upSetting;
        public AutoUpTools()
        {
            InitializeComponent();
        }

        private void Btn_Search_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folder = new FolderBrowserDialog();
            if (folder.ShowDialog() == DialogResult.OK)
            {
                this.txt_LogSavePath.Text = folder.SelectedPath.Trim();
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //初始化设置
            initSettting();
        }

        private void AutoUpTools_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //保存定时设置信息
            PrintSetInfo();
            SetTimeManager();
            MessageBox.Show("自动上传设置信息保存成功！");
        }
        private void AutoUpTools_FormClosing(object sender, FormClosingEventArgs e)
        {

        }

        private void AutoUpTools_FormClosing_1(object sender, FormClosingEventArgs e)
        {
            DialogResult result = MessageBox.Show("退出系统后，自动上报功能将不能使用", " 退出系统", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
            if (result == DialogResult.Cancel)
            {
                e.Cancel = true;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (upSetting.AutoRepeatType.Equals("仅一次"))
            {
                //停止定时器工作
                timeManager.Stop();
                string context=string.Format("【停止定时器，准备上传数据！】");
                UpLog.Log_Save(upSetting.LogPath,context);
                //开始上传数据
                
            }
            else if (upSetting.AutoRepeatType.Equals("每天"))
            {
                timeManager.Interval = 2 * 60 * 1000;
                string context = string.Format("【设置定时器24小时候唤醒，准备上传数据】");
                UpLog.Log_Save(upSetting.LogPath,context);
                ////设置定时器时间：+24小时
                timeManager.Interval = 24 * 3600000;
                //开始上传数据
                
            }
            else if(upSetting.AutoRepeatType.Equals("每周"))
            {
                string context = string.Format("【设置定时器7天后唤醒，准备上传数据】");
                UpLog.Log_Save(upSetting.LogPath, context);
                //设置定时器时间：7*24小时
                timeManager.Interval = 7*24 * 3600000;
                //开始上传数据
            }
            //开始上传数据
            AutoUpFile();
        }

        private void com_RepeatType_SelectedIndexChanged(object sender, EventArgs e)
        {
            upSetting.AutoRepeatType = com_RepeatType.SelectedItem.ToString();
        }
        #region 自定义处理函数
        /// <summary>
        /// 初始化设置信息
        /// </summary>
        private void initSettting()
        {
            upSetting = new UpSetting();
            com_RepeatType.SelectedIndex = 1;
            com_RepeatType.BackColor = Color.White;
            string exePath = System.Environment.CurrentDirectory;
            upSetting.LogPath = string.Format(@"{0}\Logs\", exePath);
            //初始化时间设置信息
            number_hour.Value = 23;
            number_minute.Value = 0;
            //绑定setting对象和控件Value
            BandSettingValue();
            //设置界面初始化打印信息
            this.txt_LogSavePath.ReadOnly = true;
            this.txt_LogSavePath.BackColor = Color.White;
            StringBuilder bulid = new StringBuilder();
            PrintSetInfo();
            //启动定时器
            SetTimeManager();
        }
        /// <summary>
        /// 把设置控件的值和Setting对象属性绑定
        /// </summary>
        private void BandSettingValue()
        {
            //绑定日志保存路径
            this.txt_LogSavePath.DataBindings.Add("Text", upSetting, "LogPath", false, DataSourceUpdateMode.OnPropertyChanged);
            //绑定时间设置
            this.number_hour.DataBindings.Add("Value", upSetting, "Setting_Hours", false, DataSourceUpdateMode.OnPropertyChanged);
            this.number_minute.DataBindings.Add("Value", upSetting, "Setting_Minute", false, DataSourceUpdateMode.OnPropertyChanged);
            //绑定重复类型
            upSetting.AutoRepeatType = com_RepeatType.SelectedItem.ToString();
        }
        /// <summary>
        /// 开始数据上报
        /// </summary>
        private void AutoUpFile()
        {
            XmlClass xml;
            try
            {
                string prtStr = string.Format("{0}:数据上报中。。。\n",DateTime.Now.ToString());
                resultBox.Text+=prtStr;
                xml = new XmlClass();
                xml.UpToDoBox(upSetting.LogPath);
                prtStr = string.Format("{0}:数据上报结束。。。\n", DateTime.Now.ToString());
                resultBox.Text += prtStr;
                prtStr = string.Format("备注:数据上报的具体信息可以在配置的日志文件保存路径下面查看\n");
                resultBox.Text += prtStr;
            }
            catch (Exception ex)
            {
                ExceptionLog.WriteExceptionLog(ex);
                string exstr = string.Format("数据自动上传失败：{0}", ex.ToString());
                UpLog.Log_Save(upSetting.LogPath, exstr);
                MessageBox.Show(exstr, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
        /// <summary>
        /// 设置初始化定时器
        /// </summary>
        private void SetTimeManager()
        {
            timeManager.Stop();
            DateTime now = DateTime.Now;
            string year = now.ToString("yyyy");
            string month = now.ToString("MM");
            string day = now.ToString("dd");
            string hour = now.ToString("HH");
            string minute = now.ToString("mm");
            string second = now.ToString("ss");
            int H = 0;
            int M = 0;
            int.TryParse(hour, out H);
            int.TryParse(minute, out M);
            DateTime setting = new DateTime(int.Parse(year), int.Parse(month), int.Parse(day), (int)upSetting.Setting_Hours, (int)upSetting.Setting_Minute, 0);
            #region 三种重复模式设置定时器时间一样
            setting.AddDays(Convert.ToDouble(now.Day));
            TimeSpan span = setting - now;
            if (span.Hours < 0)
            {
                DateTime nextTime = new DateTime(int.Parse(year), int.Parse(month), int.Parse(day) + 1, (int)upSetting.Setting_Hours, (int)upSetting.Setting_Minute, 0);
                span = new TimeSpan();
                span = nextTime - now;
            }
            TimeTrigSet(span);
            timeManager.Start();
            string context = string.Format("启动定时器，时间间隔:{0}毫秒后开始自动上报项目数据！", timeManager.Interval.ToString());
            UpLog.Log_Save(upSetting.LogPath, context);
            #endregion
        }
        /// <summary>
        /// 计算定时器定时时间
        /// </summary>
        /// <param name="Span"></param>
        private void TimeTrigSet(TimeSpan Span)
        {
            if (Span.Seconds != 0)

                timeManager.Interval = (Span.Hours * 60 + Span.Minutes) * 60000 + Math.Abs(Span.Seconds) * 1000;
            else
            {
                timeManager.Interval = 1000;
            }
        }
        /// <summary>
        /// 打印设置信息
        /// </summary>
        private void PrintSetInfo()
        {
            resultBox.Text = "";
            string print = string.Format("项目数据上报时间:{0}点{1}分\n重复类型:{2}\n日志文件保存路径：{3}\n", number_hour.Value.ToString(), number_minute.Value.ToString(), com_RepeatType.SelectedItem.ToString(), txt_LogSavePath.Text.Trim());
            resultBox.Text = print;
        }
        #endregion
    }
}
